package cn.bone.mqtt.config;

import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;

import javax.jms.Topic;

/**
 * Created by MD-01 on 2017/3/14.
 */
@Configuration
public class Config {

    @Bean(name="myTopic")
    public Topic topic(){
        return new ActiveMQTopic("bone_demo_mqtt_topic");
    }

    //连接服务器的bean
    @Bean(name="clientFactory")
    public DefaultMqttPahoClientFactory clientFactory(){
        DefaultMqttPahoClientFactory factory =
                new DefaultMqttPahoClientFactory();
        factory.setUserName("admin");
        factory.setPassword("admin");
        factory.setServerURIs("tcp://127.0.0.1:1883");
        return factory;
    }

    //发送消息的bean
    @Bean(name="mqtt")
    public MqttPahoMessageHandler mqttPahoMessageHandler(){
        MqttPahoMessageHandler handler =
                new MqttPahoMessageHandler("cyl_20170314",clientFactory());
        return handler;
    }

    //接收消息的通道
    @Bean
    public MessageChannel mqttInputChannel() {
        return new DirectChannel();
    }
    //接收消息的bean
    @Bean
    public MessageProducer inbound() {
        MqttPahoMessageDrivenChannelAdapter adapter =
                new MqttPahoMessageDrivenChannelAdapter(
                        "tcp://localhost:1883",
                        "cyl2_20170314",
                        "bone_demo_mqtt_topic");
        adapter.setCompletionTimeout(5000);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(1);
        adapter.setOutputChannel(mqttInputChannel());
        return adapter;
    }

}
